package com.saint.news;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.saint.news.Utils.AppUtils;
import com.saint.news.Utils.FileUtils;
import com.saint.news.Utils.GlideUtil;
import com.saint.news.Utils.HttpService;
import com.saint.news.Utils.HttpUtil;
import com.saint.news.adapter.MenuAdapter;
import com.saint.news.bean.CatsBean;
import com.saint.news.bean.DataBean;
import com.saint.news.bean.MainBean;
import com.saint.news.bean.SubCatsBean;
import com.saint.news.widget.MyTextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    public static final int HANDLER_GET_SUB_DATA = 1;
    public static final int HANDLER_GET_SUB_CONTENT = 2;
    private static final int UPDATE_START_CODE = 3;
    private static final int UPDATE_PROGRESS_CODE = 4;
    private static final int UPDATE_END_CODE = 5;
    private static final int UPDATE_FAIL = 6;
    public static AssetFileDescriptor fd;// 按键播放音文件
    public static String url;//接口地址
    private Activity act;
    private Toast toast;

    private ImageView ivMianBg, ivSubBg;
    private MyTextView tvTitle;
    private ListView listViewMenu;
    private ListView listViewSubmenu;
    private TextView tvExit, tvBack;
    private RelativeLayout rlRightLayout;

    private Call<String> mainCall, catsCall, subCatsCall;
    private Callback<String> mainCallBack, catsCallBcak, subCatsCallBack;
    private MainBean.DataBean mainBean;
    private CatsBean catsBean;
    private SubCatsBean subCatsBean;
    private MenuAdapter menuAdapter, submenuAdapter;
    private Handler handler;
    private static int menuIndex;
    private Drawable mainDrawable, subDrawable;
    private RelativeLayout rlTitle;

    private Callback<ResponseBody> downloadCallback;
    private String apkName;

    //下载子线程
    private Thread downLoadThread;

    //前一次更新的进度
    private int preProgress;
    private TextView tvUpdateTips, tvCancel, tvEnter;
    private Dialog updateDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        act = this;
        initView();
        initCallBack();
        initHandler();
        initData();

    }


    private void initView() {
        ivMianBg = findViewById(R.id.iv_main_bg);
        tvTitle = findViewById(R.id.tv_title);
        listViewMenu = findViewById(R.id.list_view_menu);
        listViewSubmenu = findViewById(R.id.list_view_submenu);
        rlTitle = findViewById(R.id.rl_title);
        listViewMenu.setItemsCanFocus(true);
        listViewSubmenu.setItemsCanFocus(true);
        ivSubBg = findViewById(R.id.iv_sub_bg);
        rlRightLayout = findViewById(R.id.rl_right_layout);
        tvExit = findViewById(R.id.tv_exit);
        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                finish();
                onBackPressed();
            }
        });

        tvBack = findViewById(R.id.tv_back);

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listViewMenu.setFocusable(true);
                listViewMenu.setItemsCanFocus(true);
                tvExit.setFocusable(true);
                rlRightLayout.setVisibility(View.GONE);
                listViewMenu.setSelection(menuIndex);
                tvBack.setFocusable(false);
            }
        });

        listViewMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Message msg = handler.obtainMessage();
                msg.what = MainActivity.HANDLER_GET_SUB_DATA;
                msg.arg1 = i;
                handler.handleMessage(msg);
            }
        });

        listViewSubmenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String imgUrl = subCatsBean.getData().get(i).thumb;
                if (!TextUtils.isEmpty(imgUrl)) {
                    GlideUtil.loadImg(act, imgUrl, ivSubBg, subDrawable, subDrawable);
                } else {
                    Log.e("LoadingIMG", "加载图片地址：null");
                    GlideUtil.loadImg(act, R.drawable.a_sub_bg, ivSubBg);
                }
                if (listViewMenu.getItemsCanFocus()) {
                    listViewMenu.setFocusable(false);
                    listViewMenu.setItemsCanFocus(false);
                    tvExit.setFocusable(false);
                    tvBack.setFocusable(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        listViewSubmenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Message msg = handler.obtainMessage();
                msg.what = MainActivity.HANDLER_GET_SUB_CONTENT;
                msg.arg1 = i;
                handler.handleMessage(msg);
            }
        });

    }

    private void initCallBack() {
        mainCallBack = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
                    mainBean = new Gson().fromJson(response.body(), MainBean.class).getData();
                    if (!TextUtils.isEmpty(mainBean.getCat_bg())) {
                        GlideUtil.loadImg(act, mainBean.getCat_bg(), ivMianBg, mainDrawable, mainDrawable);
                    }
                    if (!TextUtils.isEmpty(mainBean.getCat_desc_color()) && mainBean.getCat_desc_color().length() == 6) {
                        tvTitle.setTextColor(Color.parseColor("#" + mainBean.getCat_desc_color()));
                    }
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvTitle.getLayoutParams();
                    if (mainBean.getCat_desc_pos_x() > 0) {
                        params.leftMargin = mainBean.getCat_desc_pos_x();
                        params.rightMargin = mainBean.getCat_desc_pos_x();
                    }
                    if (mainBean.getCat_desc_pos_y() > 0) {
                        params.topMargin = mainBean.getCat_desc_pos_y();
                    }
//                    params.setMargins(100, 150, 100, 0);
                    tvTitle.setLayoutParams(params);
                    if (mainBean.getCat_desc_size() > 0) {
                        tvTitle.setTextSize(mainBean.getCat_desc_size());
                    }
                    tvTitle.setText(mainBean.getCat_desc());
                    if (!TextUtils.isEmpty(mainBean.getVersion()) && !TextUtils.isEmpty(mainBean.getApk())) {
                        if ("10".equals(mainBean.getVersion())) {
                            String apkUrl = mainBean.getApk();
                            if (apkUrl.startsWith("/")) {
                                apkUrl = apkUrl.substring(1, apkUrl.length());
                            }
                            showUpdateDialog(apkUrl);
                        }
                    }

                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };

        catsCallBcak = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
                    catsBean = new Gson().fromJson(response.body(), CatsBean.class);
                    setDataToView();
                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };

        subCatsCallBack = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.e("LOADINGData", "当前加载数据： " + response.body());
                if (response.isSuccessful() && null != response.body()) {
                    subCatsBean = new Gson().fromJson(response.body(), SubCatsBean.class);
                    setDataToSubTitle(subCatsBean.getData());
                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };
        //下载回调
        downloadCallback = new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    downLoadThread = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            downloadFileFromServer(response);
                        }
                    };
                    downLoadThread.start();
                } else {
                    handler.sendEmptyMessage(UPDATE_FAIL);
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                handler.sendEmptyMessage(UPDATE_FAIL);
            }
        };
    }


    private void initHandler() {
        handler = new MyHandler();
    }


    private void initData() {
        try {
            fd = act.getAssets().openFd("favorite.wav");
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = AppUtils.readAssetsTextReturnStr(this, "ip");
        mainDrawable = getResources().getDrawable(R.drawable.a_main_bg);
        subDrawable = getResources().getDrawable(R.drawable.a_sub_bg);
        getData();
    }

    private void getData() {
        mainCall = HttpUtil.getInstance(url).requestMainBean();
        mainCall.enqueue(mainCallBack);

        catsCall = HttpUtil.getInstance(url).getCats();
        catsCall.enqueue(catsCallBcak);

    }

    private void getSubCats(String catId) {
        Map<String, String> map = new HashMap<>();
        map.put("cat_id", catId);
        Log.e("HTTP", "当前加载栏目： " + catId);
        subCatsCall = HttpUtil.getInstance(url).getSubCats(map);
        subCatsCall.enqueue(subCatsCallBack);
    }


    private void setDataToView() {
        menuAdapter = new MenuAdapter(catsBean.getData(), act, handler, 1);
        listViewMenu.setAdapter(menuAdapter);
    }

    private void setDataToSubTitle(List<DataBean> children) {
        if (children.size() > 0) {
            rlRightLayout.setVisibility(View.VISIBLE);
            submenuAdapter = new MenuAdapter(children, act, handler, 2);
            listViewSubmenu.setAdapter(submenuAdapter);
            listViewSubmenu.setSelection(0);
        } else {
            tShort(R.string.str_empty);
            rlRightLayout.setVisibility(View.GONE);
        }

    }


    public void tShort(String msg) {
        if (null == toast) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setText(msg);
        }

        toast.show();

    }

    public void tShort(int resId) {
        if (null == toast) {
            toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setText(resId);
        }

        toast.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        AppUtils.play();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        tvTitle.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        super.onStart();
    }


    @Override
    protected void onStop() {
        tvTitle.setEllipsize(null);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (mainCall != null) {
            mainCall.cancel();
        }
        if (catsCall != null) {
            catsCall.cancel();
        }
        if (subCatsCall != null) {
            subCatsCall.cancel();
        }
        if (updateDialog != null) {
            updateDialog.dismiss();
        }
        super.onDestroy();
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_GET_SUB_DATA:
                    menuIndex = msg.arg1;
                    getSubCats(catsBean.getData().get(msg.arg1).id + "");
                    break;
                case HANDLER_GET_SUB_CONTENT:
                    if (null == subCatsBean.getData() || subCatsBean.getData().size() == 0) {
                        tShort(R.string.str_empty);
                    } else {
                        Intent intent = ImageListActivity.newIntent(act
                                , subCatsBean.getData().get(msg.arg1).photos_desc
                                , subCatsBean.getData().get(msg.arg1).photos_desc_color_value
                                , subCatsBean.getData().get(msg.arg1).id + ""
                                , subCatsBean.getData().get(msg.arg1).photos_desc_pos_x
                                , subCatsBean.getData().get(msg.arg1).photos_desc_pos_y
                                , subCatsBean.getData().get(msg.arg1).photos_desc_size);
                        startActivity(intent);
                    }
                    break;
                case UPDATE_START_CODE:
                    preProgress = 0;
                    if (updateDialog != null) {
                        tvUpdateTips.setText("正在下载安装包：" + preProgress + "%");
                        tvCancel.setVisibility(View.GONE);
                        tvEnter.setVisibility(View.GONE);
                    }
                    break;

                case UPDATE_PROGRESS_CODE:
                    /**
                     * 设置只有当进度等于1时并且发生改变时做更新，因为progress的值可能为1.1，1.2，1.3，但是显示的都会是1%，
                     * 如果不做判断限制那么每次UPDATE_PROGRESS_CODE回调都会更新通知内容，也就是当1.1时会更新，1.2时也会执行更新的方法，
                     * 但是前台展示的都是1%，所以做了好多无用功
                     */
                    int currProgress = (int) (100 * (float) msg.obj);
                    if (preProgress < currProgress) {
                        if (updateDialog != null) {
                            tvUpdateTips.setText("正在下载安装包：" + currProgress + "%");
                        }
                    }
                    preProgress = currProgress;

                    int progress = (int) (100 * (float) msg.obj);
                    if (updateDialog != null) {
                        tvUpdateTips.setText("正在下载安装包：" + progress + "%");
                    }
                    break;

                case UPDATE_END_CODE:
                    if (updateDialog != null && updateDialog.isShowing()) {
                        updateDialog.dismiss();
                        startActivity(openApk());
                    }
                    break;

                case UPDATE_FAIL:
                    if (updateDialog != null && updateDialog.isShowing()) {
                        updateDialog.dismiss();
                    }
                    Toast.makeText(act, "下载更新包失败", Toast.LENGTH_SHORT);
                    break;

                default:
                    break;
            }
        }
    }


    private void showUpdateDialog(final String apkUrl) {
//        updateDialog = new Dialog(act);
        updateDialog = new AlertDialog.Builder(act, R.style.Dialog_white).create();
        updateDialog.setCancelable(false);
        updateDialog.show();
        updateDialog.setContentView(R.layout.dialog_update);
        Window window = updateDialog.getWindow();

        tvUpdateTips = window.findViewById(R.id.tv_update_tips);
        tvCancel = window.findViewById(R.id.tv_cancel);
        tvEnter = window.findViewById(R.id.tv_enter);

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateDialog.dismiss();
            }
        });
        tvEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downloadUrl(apkUrl);
            }
        });

        tvEnter.setFocusable(true);
        tvEnter.setFocusableInTouchMode(true);
    }

    /**
     * @param downUrl apk地址
     */
    private void downloadUrl(String downUrl) {
        apkName = "news" + System.currentTimeMillis() + ".apk";
        HttpService instance = HttpUtil.getInstance(url);
        instance.downloadFileWithUrlAsync(downUrl)
                .enqueue(downloadCallback);
    }

    /**
     * 打开已下载的安装包
     */
    public Intent openApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(getExternalFilesDir(null), apkName);
        try {
            Log.e("HTTP", "下载文件大小： " + FileUtils.getFileSize(file));
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("HTTP", "下载文件大小： " + e.getMessage());
        }
        Uri data;
        data = Uri.fromFile(file);
        Log.e("TAG", "当前APK地址： " + data.getPath());
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        return intent;
    }

    /**
     * 从服务器获取的文件下载到本地
     *
     * @param response 服务器返回的数据
     */
    private void downloadFileFromServer(@NonNull Response<ResponseBody> response) {
        try {
            InputStream is = response.body().byteStream();
            File file = new File(getExternalFilesDir(null), apkName);
            if (file.exists() && file.isFile()) file.delete();
            handler.sendEmptyMessage(UPDATE_START_CODE);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                long all = response.body().contentLength();
                float percent = total / ((float) all);
                Message msg = new Message();
                msg.what = UPDATE_PROGRESS_CODE;
                msg.obj = percent;
                handler.sendMessage(msg);
            }
            fos.flush();
            fos.close();
            bis.close();
            is.close();
            handler.sendEmptyMessage(UPDATE_END_CODE);
        } catch (Exception e) {
            handler.sendEmptyMessage(UPDATE_FAIL);
            e.printStackTrace();
        }

    }

    @Override
    public void onBackPressed() {
        if (rlRightLayout.getVisibility() == View.VISIBLE) {
            listViewMenu.setFocusable(true);
            listViewMenu.setItemsCanFocus(true);
            tvExit.setFocusable(true);
            rlRightLayout.setVisibility(View.GONE);
            listViewMenu.setSelection(menuIndex);
            tvBack.setFocusable(false);
        } else {
            super.onBackPressed();
        }
    }
}
